package io.renren.util.weichuang;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

public class TestNotify {

    private static String publicKey = "";

    public void notifyHandle(HttpServletRequest request, HttpServletResponse response) {
        try {

            Map<String, String> notifyMap = toMap(request);
            Boolean bool = RSA2Util.rsaCheck(notifyMap, publicKey);
            if (bool) {
                printout(response);
            }
        } catch (Exception e) {
        }

    }

    private void printout(HttpServletResponse response) {
        PrintWriter out = null;
        try {
            try {
                out = response.getWriter();
            } catch (IOException e) {
            }
            out.print("success");
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }

    protected Map<String, String> toMap(HttpServletRequest request) throws Exception {
        try {
            Map<String, String> resultMap = new HashMap<String, String>();
            Map<String, String[]> paramMap = request.getParameterMap();
            for (Entry<String, String[]> entry : paramMap.entrySet()) {
                String[] values = entry.getValue();
                if (values == null) {
                    resultMap.put(entry.getKey(), "");
                } else {
                    String value = StringUtils.join(values, ";");
                    value = URLDecoder.decode(value, "UTF-8");
                    resultMap.put(entry.getKey(), value);
                }
            }
            return resultMap;
        } catch (Exception e) {
            throw new Exception();
        }
    }
}
